from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin,RetrieveModelMixin,CreateModelMixin
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.viewsets import ViewSetMixin, ViewSet
from rest_framework.response import Response
from django.http import JsonResponse
from rest_framework.decorators import  action


from .pagenation import NewPageNumberPagination
from . import models
from . import serializer
from .filters import MovieLevelFilterSet
from back.utils.response import APIResponse

# Create your views here.

# 电影
class MovieView(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    queryset = models.Movie.objects.filter(is_delete=False, is_show=True).all().order_by('id')
    serializer_class = serializer.MovieModelSerializer
    # 分页
    pagination_class = NewPageNumberPagination
    # 过滤
    filter_backends = [DjangoFilterBackend, OrderingFilter, ]
    ordering_fields = ['level', 'id']
    # filter_fields = ['movie_category']

    # 自定义的过滤类
    filter_class = MovieLevelFilterSet
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            for movie in serializer.data:
                movie['movie_img'] = 'https://' + movie.get('movie_img').split('A/')[-1]
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, *args, **kwargs):
        d = {}
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        d = dict(serializer.data)
        d['movie_img'] = 'https://' + d.get('movie_img').split('A/')[-1]

        return Response(d)


class NewMovieView(GenericViewSet, ListModelMixin):
    queryset = models.Movie.objects.filter(is_delete=False, is_show=True).all().order_by('id')
    serializer_class = serializer.MovieModelSerializer

    filter_class = MovieLevelFilterSet
    def list(self, request, *args, **kwargs):
        d = {}
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        # d = dict(serializer.data)
        for movie in serializer.data:
            movie['movie_img'] = 'https://' + movie.get('movie_img').split('A/')[-1]


        print(serializer.data)
        return Response(serializer.data)


# 电影分类
class MovieCategoryView(GenericViewSet,ListModelMixin):
    queryset = models.MovieCategory.objects.filter(is_delete=False,is_show=True).order_by('orders')
    serializer_class = serializer.MovieCategorySerializer


# 各分类电影的评分靠前的5部
class CategoryMovieView(ViewSet):

    @action(detail=False)
    def category_movie(self, request):
        d = []
        for i in range(1,14):
            objs = models.Movie.objects.filter(movie_category_id=i).order_by('orders')[:5]
            ser = serializer.MovieModelSerializer(instance=objs, many=True)
            for dic in ser.data:
                dic['movie_img'] ='https://' + dic.get('movie_img').split('A/')[-1]
            d.append(ser.data)
        return JsonResponse(d, safe=False)


# 获取所有电影中评分前5的电影
class MovieTop5View(ViewSet):

    @action(detail=False)
    def top5(self, request):
        objs = models.Movie.objects.order_by('-level')[:10]
        ser = serializer.MovieModelSerializer(instance=objs, many=True)
        for dic in ser.data:
            dic['name'] = dic.get('name').split()[0]
        return JsonResponse(ser.data, safe=False)


# 通过id获取电影详情信息
class MovieDetailView(GenericViewSet, RetrieveModelMixin):
    queryset = models.Movie.objects.all()
    serializer_class = serializer.MovieModelSerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        res = serializer.data.get('movie_img').split('A/')[-1]
        ser = dict(serializer.data)
        ser['movie_img'] = 'https://' + res
        return Response(ser)


# 电影搜索视图，通过电影名中的关键字进行搜索
class MovieSearchView(GenericViewSet,ListModelMixin):
    queryset = models.Movie.objects.filter(is_delete=False,is_show=True).order_by('-level').all()
    serializer_class = serializer.MovieModelSerializer
    pagination_class = NewPageNumberPagination

    filter_backends=[SearchFilter]
    search_fields=['name']

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            for movie in serializer.data:
                movie['movie_img'] = 'https://' + movie.get('movie_img').split('A/')[-1]
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


# 获取评论信息
class CommentView(GenericViewSet,ListModelMixin,CreateModelMixin):
    queryset = models.Comment.objects.all()
    serializer_class = serializer.CommentSerializer

    filter_backends = [DjangoFilterBackend,]
    # ordering_fields = ['level', 'id']
    filter_fields = ['movie_title']
